package master

import (
	"encoding/json"
	"gitee.com/wendyRose/DistributedCrontab/common"
	"log"
	"net"
	"net/http"
	"strconv"
	"time"
)

//任务的HTTP接口
type ApiServer struct {
	httpServer *http.Server
}

var (
	//单例
	GApiServer *ApiServer
)

//保存任务接口
func handleJobSave(resp http.ResponseWriter, req *http.Request)  {
	var (
		err error
		postJob string
		job common.Job
		oldJob *common.Job
		bytes []byte
	)

	if err = req.ParseForm(); err != nil {
		log.Panic(err)
	}

	postJob = req.PostForm.Get("job")
	if err = json.Unmarshal([]byte(postJob), &job); err != nil {
		log.Panic(err)
	}

	if oldJob, err = GJobMgr.SaveJob(&job); err != nil {
		log.Panic(err)
	}

	if bytes, err = common.BuildResponse(0, "success", oldJob); err != nil {
		log.Panic(err)
	}

	resp.Write(bytes)
	return
}

//删除任务接口
func handleJobDelete(resp http.ResponseWriter, req *http.Request)  {
	var (
		err error
		name string
		oldJob *common.Job
		bytes []byte
	)

	if err = req.ParseForm(); err != nil {
		log.Panic(err)
	}

	name = req.PostForm.Get("name")

	if oldJob, err = GJobMgr.DeleteJob(name); err != nil {
		log.Panic(err)
	}

	if bytes, err = common.BuildResponse(0, "success", oldJob); err == nil {
		resp.Write(bytes)
	}

	return
}

func handleJobList(resp http.ResponseWriter, req *http.Request)  {
	var (
		jobList []*common.Job
		err error
		bytes []byte
	)

	if jobList, err = GJobMgr.ListJob(); err != nil {
		return
	}

	if bytes, err = common.BuildResponse(0, "success", jobList); err == nil {
		resp.Write(bytes)
	}

	return
}

// 强制杀死某个任务
// POST /job/kill  name=job1
func handleJobKill(resp http.ResponseWriter, req *http.Request) {
	var (
		err error
		name string
		bytes []byte
	)

	// 解析POST表单
	if err = req.ParseForm(); err != nil {
		goto ERR
	}

	// 要杀死的任务名
	name = req.PostForm.Get("name")

	// 杀死任务
	if err = GJobMgr.KillJob(name); err != nil {
		goto ERR
	}

	// 正常应答
	if bytes, err = common.BuildResponse(0, "success", nil); err == nil {
		resp.Write(bytes)
	}
	return

ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}


//初始化服务
func InitApiServer() (err error) {
	var (
		mux *http.ServeMux
		listener net.Listener
		httpServer *http.Server
	)

	//配置路由
	mux = http.NewServeMux()
	mux.HandleFunc("/job/save", handleJobSave)
	mux.HandleFunc("/job/delete", handleJobDelete)
	mux.HandleFunc("/job/list", handleJobList)
	mux.HandleFunc("/job/kill", handleJobKill)

	//启动TCP监听
	if listener, err = net.Listen("tcp", ":" + strconv.Itoa(GConfig.ApiPort)); err != nil {
		return
	}

	//创建一个HTTP服务
	httpServer = &http.Server{
		ReadTimeout:      time.Duration(GConfig.ApiReadTimeout) * time.Microsecond,
		WriteTimeout:      time.Duration(GConfig.ApiWriteTimeout) * time.Microsecond,
		Handler: mux,
	}

	//赋值单例
	GApiServer = &ApiServer{
		httpServer: httpServer,
	}

	go httpServer.Serve(listener)

	return
}
